package com.example.springai.controller;

import java.util.*;

public class OpenAIClient {
    private static final List<Tool> tools = Arrays.asList(
            new Tool("function", new Tool.Function(
                    "get_weather",
                    "Get weather of a location; the user should supply a location first.",
                    new Tool.Function.Parameters(
                            "object",
                            Map.of("location", new Tool.Function.Parameters.Property("string", "The city and state, e.g., San Francisco, CA")),
                            List.of("location")
                    )
            ))
    );

    public static String sendMessages(List<Map<String, Object>> messages) {
        // 模拟调用 OpenAI API
        Map<String, Object> response = simulateOpenAIRequest(messages);

        // 检查是否有工具调用
        if (response.containsKey("tool_calls")) {
            System.out.println("Tool call detected.");
            Map<String, Object> toolCall = (Map<String, Object>) ((List<?>) response.get("tool_calls")).get(0);
            Map<String, Object> function = (Map<String, Object>) toolCall.get("function");

            // 调用工具处理逻辑
            String toolResponse = ToolCallHandler.handleToolCall(
                    (String) function.get("name"),
                    (String) function.get("arguments")
            );

            // 将工具的响应添加到消息列表
            messages.add(Map.of(
                    "role", "assistant",
                    "content", null,
                    "tool_calls", response.get("tool_calls")
            ));
            messages.add(Map.of(
                    "role", "tool",
                    "tool_call_id", toolCall.get("id"),
                    "content", toolResponse
            ));

            // 再次发送消息并返回最终响应
            response = simulateOpenAIRequest(messages);
        }

        return (String) response.get("content");
    }

    private static Map<String, Object> simulateOpenAIRequest(List<Map<String, Object>> messages) {
        // 模拟 OpenAI API 的返回结果
        if (messages.get(messages.size() - 1).get("role").equals("user")) {
            return Map.of(
                    "tool_calls", List.of(Map.of(
                            "id", "call_123",
                            "function", Map.of(
                                    "name", "get_weather",
                                    "arguments", "{\"location\":\"Hangzhou\"}"
                            )
                    ))
            );
        } else {
            return Map.of(
                    "content", "The weather in Hangzhou is 35 °C."
            );
        }
    }
}
